package com.example.demo.task;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * @Author tyy
 * @Description [面试:如何实现动态定时任务？](https://www.bilibili.com/video/BV1cT4y1Q7wN)
 * @Since 2022/2/27
 */
@Configuration
//@EnableScheduling // 开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer {

    /**执行定时任务
     * @param registrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar registrar) {
        registrar.addTriggerTask(
                // 执行内容
                () -> System.out.println("\n-->动态定时任务执行：registrar = " + LocalDateTime.now().toLocalTime()),
                // 执行周期
                triggerContext -> {
                    String cron = "0/3 * * * * ?";
                    System.out.println("数据库设置的定时任务表达式：cron = " + cron);
                    if (!StringUtils.hasText(cron)) {
                        System.out.println("没有设置定时任务表达式");

                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                });

    }
}
